package com.work.customer.service.impl;

import com.work.customer.dao.MenuMapper;
import com.work.customer.dao.RoleMapper;
import com.work.customer.pojo.Menu;
import com.work.customer.pojo.Role;
import com.work.customer.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private RoleMapper roleMapper;

    //查询所有权限
    @Override
    public List<Menu> find(Integer rid) {
        List<Menu> list = new ArrayList<>();

        Role role = roleMapper.selectByPrimaryKey(rid);
        //通过角色id查询中间表获取权限id
        Integer[] mids = roleMapper.findByRid(role.getId());
        //查询该角色所拥有的权限
        for (Integer mid : mids) {
            Menu menu = menuMapper.selectByPrimaryKey(mid);
            list.add(menu);
        }
        return list;
    }

    //给角色添加权限
    @Override
    public void add(Integer rid,Integer[] mids) {
        //向中间表插入数据
        for (Integer mid : mids) {
            roleMapper.add(rid,mid);
        }
    }

    //给角色删除权限
    @Override
    public void delete(Integer rid, Integer[] mids) {
        //删除角色权限中间表数据
        for (Integer mid : mids) {
            roleMapper.deleteById(rid,mid);
        }
    }

    //修改角色权限
    @Override
    public void update(Integer rid, Integer[] mids) {
        //获取角色原有权限id
        Integer[] mids1 = menuMapper.findByRid(rid);
        if(mids.length>0){
            //向中间表删除数据
            this.delete(rid,mids1);
            //向中间表重新添加数据
            this.add(rid,mids);
        }
    }
}
